import { useReady } from '@tarojs/taro'
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react'
import { AtLoadMore } from 'taro-ui'

import './index.scss'

interface QueryParams {
    [key:string] : any
}

interface Props {
    onClick : {
        (queryParams : QueryParams) : Promise<any[]>
    };

    keyName? : string;
    pageSize? : number;
    reload? : any;
    queryParams? : QueryParams;

    onFinish? : {
        (rows : any[]) : void
    };

    //[key : string] : any;
}


export default forwardRef((props:Props, ref) => {
    const keyName = props.keyName || 'id'
    let [pageNo, setpageNo] = useState(0)
    let [status, setStatus] = useState<	'more' | 'loading' | 'noMore'>('more')
    let [tmp, setTmp] = useState<any>(null)
    async function load() {
        if(status != 'more') return
        let query:QueryParams = {...(props.queryParams || {})}
        query.lastKey = pageNo
        query.pageSize = props.pageSize || 10

        setStatus('loading')
        let rows = await props.onClick(query)
        if(rows.length > 0) {
            setpageNo(rows[rows.length - 1][keyName])
        }


        if(rows.length < query.pageSize) {
            setStatus('noMore')
        }else {
            setStatus('more')
        }

        if(props.onFinish) {
            props.onFinish(rows)
        }
    }

    useImperativeHandle(ref, () => {
        return {
            reLoad : () => {
                setTmp((new Date()).toLocaleString())
                setpageNo(0)
                setStatus('more')
            }
        }
    }, [props.queryParams])

    useReady(() => {
        //load()
    })

    useEffect(() => {
        load()
    }, [tmp])


    return (
        <>
            <AtLoadMore status={status} moreBtnStyle='border:none;' onClick={() => load()}></AtLoadMore>
        </>
    )
})